const fs = require("fs");
const path = require("path");
const utils = require("../utils/utils");

class FileController {
    // form表单直传
    async fileUpload(ctx) {
        const files = ctx.request.files.file;

        if(files instanceof Array) {
            for(let file of files) {
                const reader = fs.createReadStream(file.path);
                let filePath = path.join(__dirname, "../cache/file1/") + `/${utils.uuid()}.${file.name.split(".").pop()}`;

                const upStream = fs.createWriteStream(filePath);
                reader.pipe(upStream);
            }
        } else {
            const reader = fs.createReadStream(files.path);
            let filePath = path.join(__dirname, "../cache/file1/") + `/${utils.uuid()}.${files.name.split(".").pop()}`;

            const upStream = fs.createWriteStream(filePath);
            reader.pipe(upStream);
        }

        ctx.body = {
            code: 200,
            message: "上传成功"
        }
    }
}

module.exports = FileController;